#
# opentome_cbz.py
# (c) 2008 Will Baker.
#

import UnRAR

def opentome_cbr_load_all_pages( loader, comic ):
    files = {}
    
    archive = UnRAR.Archive( comic.path )
    for f in archive.iterfiles():
        if not f.isdir and comic.is_supported_image_format(f.filename):
            files[f.filename] = f.open('rb').read()
            
    loader.on_page_count_loaded( comic, len(files) )
    
    filenames = files.keys()
    comic.sort_pages( filenames )
    page = 0
    for f in filenames:
        loader.on_page_data_loaded( comic, f, page, files[f] )
        page += 1
     
def opentome_cbr_load_single_page( loader, comic, page ):
        archive = UnRAR.Archive( comic.path )
        files = []
        
        for f in archive.iterfiles():
            if not f.isdir and comic.is_supported_image_format(f.filename):
                files.append( f.filename )
                
        loader.on_page_count_loaded( comic, len(files) )

        comic.sort_pages( files )
        archive = None
        
        archive = UnRAR.Archive( comic.path )
        for f in archive.iterfiles():
            if f.filename == files[page]:
                loader.on_page_data_loaded( comic, f.filename, page, f.open('rb').read() )
                return    
       
def opentome_register_plugin():
    return {
        'extensions'       : ['.cbr', '.rar'],
        'load_all_pages'   : opentome_cbr_load_all_pages,
        'load_single_page' : opentome_cbr_load_single_page,
        'pool'             : 1
    }
